// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// --- *** 新增：管理员 OPENID *** ---
const ADMIN_OPENID = '41b03074e1bb154e164f0a56873bf6d0';

// 云函数入口函数
exports.main = async (event, context) => {
  
  // --- *** 新增：权限校验 *** ---
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;

  if (openid !== ADMIN_OPENID) {
    // 如果不是管理员，返回错误
    // 实际项目中，这里也可以查询 admins 集合
    return {
      success: false,
      message: '无权访问'
    };
  }
  // --- *** 权限校验结束 *** ---

  try {
    // (原有的统计逻辑)
    const totalOrdersRes = await db.collection('orders').count();
    const pendingOrdersRes = await db.collection('orders').where({ printStatus: 'pending' }).count();
    const completedOrdersRes = await db.collection('orders').where({ printStatus: 'completed' }).count();
    
    const totalIncomeRes = await db.collection('orders').aggregate()
      .group({
        _id: null,
        total: db.command.sum('$totalPrice')
      }).end();

    return {
      success: true,
      stats: {
        totalOrders: totalOrdersRes.total,
        pendingOrders: pendingOrdersRes.total,
        completedOrders: completedOrdersRes.total,
        totalIncome: totalIncomeRes.list.length > 0 ? totalIncomeRes.list[0].total.toFixed(2) : 0
      }
    }
  } catch (e) {
    return {
      success: false,
      error: e
    }
  }
}